package com.laf.mobile.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laf.common.constant.MQConstant;
import com.laf.common.core.domain.entity.MobileUser;
import com.laf.common.core.domain.model.LoginMobileUser;
import com.laf.common.enums.DelFlagEnum;
import com.laf.common.enums.SMSTypeEnum;
import com.laf.common.enums.UserStatusEnum;
import com.laf.common.exception.ServiceException;
import com.laf.common.utils.SMSUtil;
import com.laf.common.utils.SecurityUtils;
import com.laf.common.utils.StringUtils;
import com.laf.common.utils.mq.RabbitMqHelper;
import com.laf.mobile.domain.dto.*;
import com.laf.mobile.mapper.MobileUserMapper;
import com.laf.mobile.service.IMobileUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class MobileUserServiceImpl extends ServiceImpl<MobileUserMapper, MobileUser> implements IMobileUserService {

    private final SMSUtil smsUtil;

    private final RabbitMqHelper rabbitMqHelper;

    /**
     * 根据用户名查询用户
     *
     * @param userName 用户名
     * @return
     */
    @Override
    public MobileUser selectUserByUserName(String userName) {
        return baseMapper.selectUserByUserName(userName);
    }


    /**
     * 查询用户管理列表
     *
     * @param user 用户管理
     * @return 用户管理
     */
    @Override
    public List<MobileUser> selectUserList(MobileUser user) {
        return getBaseMapper().selectList(buildQueryWrapper(user));
    }

    /**
     * 更新用户的登录信息
     *
     * @param dto
     */
    @Override
    public void updateLogInfo(MobileUserLoginDTO dto) {
        this.lambdaUpdate()
                .eq(MobileUser::getUserName, dto.getUsername())
                .set(MobileUser::getUpdateTime, LocalDateTime.now())
                .set(MobileUser::getCId, dto.getCid())
                .set(MobileUser::getClientPlatform, dto.getClientPlatform())
                .update();
    }

    /**
     * 用户注册
     *
     * @param dto 注册参数
     */
    @Override
    public void register(MobileUserRegisterDTO dto) {
        // 1. 校验短信认证码
        smsUtil.checkSms(dto.getUserName(), dto.getCode(), SMSTypeEnum.REGISTER);
        // 校验成功删除验证码
        smsUtil.removeSms(dto.getUserName(), SMSTypeEnum.REGISTER);

        // 2. 校验账号是否存在
        MobileUser user = lambdaQuery().eq(MobileUser::getUserName, dto.getUserName())
                .eq(MobileUser::getDelFlag, DelFlagEnum.NORMAL)
                .one();
        if (user != null) {
            throw new ServiceException("账号已存在");
        }

        // 对密码进行加密
        String pwd = SecurityUtils.encryptPassword(dto.getPassword());

        // 3.新增用户
        MobileUser insertUser = new MobileUser(dto.getUserName(), pwd);
        boolean b = save(insertUser);
        if (!b) {
            throw new ServiceException("注册失败");
        }

    }


    /**
     * 获取登录用户信息
     *
     * @return
     */
    @Override
    public MobileUser getUserInfo() {
        // 1. 查询用户
        Long userId = SecurityUtils.getMobileUserId();
        MobileUser user = getById(userId);

        // 2. 校验用户
        if (user == null) throw new ServiceException("用户不存在");
        // checkUser(user);

        user.setPassword(null);
        return user;
    }


    /**
     * 更新用户信息
     *
     * @param dto
     */
    @Override
    public void updateUserInfo(UpdateMobileUserDTO dto) {
        // 1. 校验用户
        Long userId = SecurityUtils.getMobileUserId();
        MobileUser user = getById(userId);
        if (user == null) throw new ServiceException("用户不存在");
        checkUser(user);

        //2. 更新用户信息
        boolean b = lambdaUpdate()
                .eq(MobileUser::getUserId, userId)
                .set(MobileUser::getNickName, dto.getNickName())
                .set(MobileUser::getEmail, dto.getEmail())
                .set(MobileUser::getSex, dto.getSex())
                .set(MobileUser::getAvatar, dto.getAvatar())
                .update();
        if (!b) throw new ServiceException("更新用户信息失败");

    }

    /**
     * 重置密码
     *
     * @param dto
     */
    @Override
    public void resetPwd(ReSetPwdDTO dto) {
        // 验证验证码
        smsUtil.checkSms(dto.getPhone(), dto.getCode(), SMSTypeEnum.FORGET_PASSWORD);

        // 校验用户
        MobileUser user = lambdaQuery().eq(MobileUser::getUserName, dto.getPhone()).one();
        if (user == null) throw new ServiceException("用户不存在");
        checkUser(user);

        // 重置密码
        String pwd = SecurityUtils.encryptPassword(dto.getPassword());
        boolean b = lambdaUpdate()
                .eq(MobileUser::getUserId, user.getUserId())
                .set(MobileUser::getPassword, pwd)
                .update();
        if (!b) throw new ServiceException("重置密码失败");

    }

    /**
     * 修改密码
     *
     * @param dto 修改密码参数
     */
    @Override
    public void updatePwd(UpdatePwdDTO dto) {
        // 1. 校验账号
        Long userId = SecurityUtils.getMobileUserId();
        MobileUser user = getById(userId);
        if (user == null) throw new ServiceException("用户不存在");
        checkUser(user);

        // 2. 校验密码
        boolean flag = SecurityUtils.matchesPassword(dto.getOldPwd(), user.getPassword());
        if (!flag) throw new ServiceException("旧密码错误");

        //3. 更新数据库
        String pwd = SecurityUtils.encryptPassword(dto.getNewPwd());
        boolean b = lambdaUpdate()
                .eq(MobileUser::getUserId, userId)
                .set(MobileUser::getPassword, pwd)
                .update();

        if (!b) throw new ServiceException("更新密码失败");
    }

    @Override
    public void logout() {
        LoginMobileUser mobileLoginUser = SecurityUtils.getMobileLoginUser();
        // 删除用户
        Long userId = mobileLoginUser.getUserId();
        removeById(userId);

        // 删除其他信息 1. 失物信息 2. 动态 3. 评论 4. 收藏 5. es
        rabbitMqHelper.sendMessage(
                MQConstant.USER_EXCHANGE,
                MQConstant.USER_DELETE_ROUTING_KEY,
                userId
        );

    }


    /**
     * 构建查询条件
     *
     * @param query 查询条件
     * @return 查询条件
     */
    private LambdaQueryWrapper<MobileUser> buildQueryWrapper(MobileUser query) {
        LambdaQueryWrapper<MobileUser> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(query.getUserName()), MobileUser::getUserName, query.getUserName());
        lqw.like(StringUtils.isNotBlank(query.getNickName()), MobileUser::getNickName, query.getNickName());
        lqw.like(StringUtils.isNotBlank(query.getEmail()), MobileUser::getEmail, query.getEmail());
        lqw.eq(StringUtils.isNotBlank(query.getSex()), MobileUser::getSex, query.getSex());
        lqw.eq(query.getStatus() != null, MobileUser::getStatus, query.getStatus());
        lqw.orderByDesc(MobileUser::getCreateTime);
        return lqw;
    }

    /**
     * 检验用户是否有效
     */
    public void checkUser(MobileUser user) {
        if (user.getStatus().equals(UserStatusEnum.LOCKED.getCode())) {
            log.error("用户被锁定");
            throw new ServiceException("用户被锁定");
        }
        if (user.getDelFlag().equals(DelFlagEnum.DELETED.getCode())) {
            log.error("用户不存在");
            throw new ServiceException("用户不存在");
        }

    }

}
